package upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Uploads
 */
@WebServlet("/upload/Uploads")
public class Uploads extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Uploads() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setHeader("Content-Type", "text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String path = this.getServletContext().getRealPath("/WEB-INF/upload");
		File file = new File(path);
		if(!file.exists()){
			file.mkdir();
		}
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
		upload.setHeaderEncoding("UTF-8");
		List<FileItem> lists;
		try {
			lists = upload.parseRequest(request);
			for(FileItem fileItem:lists){
				String fileName = fileItem.getName();
				System.out.println(fileName);
				InputStream ip = fileItem.getInputStream();
				String str = path+"//"+fileName;
				System.out.println(str);
				FileOutputStream fos = new FileOutputStream(str);
				byte[] b = new byte[1024];
				int len = 0;
				while(ip.read(b)>0){
					fos.write(b, 0, len);
				}
			}
			out.println("上传成功");
		} catch (org.apache.commons.fileupload.FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
